<?php

namespace control;
/*
*销售发货明细表类
*/

class saleSendOrderMxClass extends adIndexClass
{
    private const page = 'saleSendOrderMx';
    private const title = '销售发货明细表';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'recordDate'      => [
                        'name'  => '单据日期',
                        'width' => 100,
                        'sort'  => 1,
                    ],
                    'orderNo'         => [
                        'name'  => "销售发货单号",
                        'width' => 200,
                        'sort'  => 1,
                    ],
                    'saleOrder'       => [
                        'name'  => "销售单号",
                        'width' => 200,
                    ],
                    'contract'        => [
                        'name'  => '合同编号',
                        'width' => 200,
                    ],
                    'companyName'     => [
                        'name'  => '客户',
                        'width' => 100,
                    ],
                    'manager'         => [
                        'name'  => '销售员',
                        'width' => 100,
                    ],
                    'code'            => [
                        'name'  => '产品编码',
                        'width' => 100,
                        'sort'  => 1,
                    ],
                    'materialName'    => [
                        'name'  => '产品名称',
                        'width' => 100,
                    ],
                    'model'           => [
                        'name'  => '规格型号',
                        'width' => 100,
                        'sort'  => 1,
                    ],
                    'unit'            => [
                        'name'  => '单位',
                        'width' => 100,
                    ],
                    'num'             => [
                        'name'  => '发货数量',
                        'width' => 100,
                        'sort'  => 1,
                    ],
                    'price'           => [
                        'name'  => '单价(' . static::$unit . ')',
                        'width' => 100,
                        'sort'  => 1,
                    ],
                    'moneyWithOutTax' => [
                        'name'  => '未税金额(' . static::$unit . ')',
                        'width' => 120,
                        'sort'  => 1,
                    ],
                    'rate'            => [
                        'name'  => '税率',
                        'width' => 100,
                        'sort'  => 1,
                    ],
                    'taxMoney'        => [
                        'name'  => '税额(' . static::$unit . ')',
                        'width' => 100,
                        'sort'  => 1,
                    ],
                    'money'           => [
                        'name'  => '价税合计(' . static::$unit . ')',
                        'width' => 120,
                        'sort'  => 1,
                    ],
                    'text'            => [
                        'name'  => '备注',
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "销售发货单号" => text(array("name" => "orderNo")),
                    "合同编号"   => text(array("name" => "contractNo")),
                    "销售订单号"  => text(array("name" => "saleNo")),
                ],
                [
                    "产品编码" => text(array("name" => "code")),
                    "产品名称" => text(array("name" => "materialName")),
                    '客户名称' => clientProfileClass::kehuSelect(array('title' => '')),
                ],
                [
                    '销售员'  => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']),
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ], 1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .= "<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'" . self::page . "'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "b.orderNo" => $this->post('orderNo'),//证件编号
            "c.name"    => $this->post('materialName'),
            "c.code"    => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            "b.manager" => $this->post('stid'),
            "b.khid"    => $this->post('khid'),
            "a.coid"    => self::$coid,
            "b.state"   => '已确认'
        );
        $and   = "";
        if ($this->post('contractNo')) {
            $and .= " and b.contractId in (select id from sales_contract where orderNo like '%" . $this->post('contractNo') . "%' and coid = '" . self::$coid . "')";
        }
        if ($this->post('saleNo')) {
            $and .= " and a.saleOrderMxId in (select id from sale_order_detail where orderId in (select id from sale_order where orderNo like '%" . $this->post('saleNo') . "%' and coid = '" . self::$coid . "'))";
        }
        if ($this->post('createTime')) {
            //单据日期
            $and .= self::timeComparison($this->post('createTime'), field: 'b.recordDate');
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        //排序
        $orderBy                     = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'a.time desc,a.list',
            "sort"   => $this->post('list_sort') ?: "asc",
            "array"  => array(),
        ));
        $page                        = $this->page(array(
            "table" => "sale_send_order_detail as a join sale_send_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'field' => "a.*,b.orderNo,b.recordDate,b.contractId,b.khid,c.code,c.name as materialName,c.model,b.actual_delivery_date,b.manager,b.text",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate   = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "orderNo":
                        $row[] = componentClass::urlTitle($array['orderNo'], root . 'control/adIndex.html?cla=saleSendOrder&fun=detail&id=' . $array['orderId'], '销售发货单', 'hands-url');
                        break;
                    case "saleOrder":
                        $saleOrderMx = query('sale_order_detail', "id = '$array[saleOrderMxId]'");
                        $saleOrder   = query('sale_order', "id = '$saleOrderMx[orderId]'");
                        $row[]       = componentClass::urlTitle($saleOrder['orderNo'], root . 'control/adIndex.html?cla=saleOrder&fun=detail&id=' . $saleOrder['id'], '销售订单', 'hands-url');
                        break;
                    case "contract":
                        $contract = query('sales_contract', "id = '$array[contractId]'");
                        $row[]    = $contract['orderNo'];
                        break;
                    case "companyName":
                        $kehu  = query('kehu', "khid = '$array[khid]'");
                        $row[] = $kehu['companyName'];
                        break;
                    case "manager":
                        $row[] = self::findStaff($array['manager']);
                        break;
                    case "num":
                        $row[] = self::lostZero($array['num'], 'numPrecision');
                        break;
                    case "price":
                        $row[] = self::lostZero($array['price'], 'pricePrecision');
                        break;
                    case "moneyWithOutTax":
                    case "taxMoney":
                    case "money":
                        $row[] = self::lostZero($array[$key]);
                        break;
                    case "rate":
                        $row[] = ($array['rate'] * 100) . '%';
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $numTotal = find([
            'table'  => "sale_send_order_detail as a join sale_send_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'single' => $where,
            'field'  => "ifnull(sum(a.num),0) as num,ifnull(sum(a.moneyWithOutTax),0) as moneyWithOutTax,ifnull(sum(a.taxMoney),0) as taxMoney,ifnull(sum(a.money),0) as money",
        ]);
        $total    = [
            'num'             => self::lostZero($numTotal['num'], 'numPrecision'),
            'moneyWithOutTax' => self::lostZero($numTotal['moneyWithOutTax']),
            'taxMoney'        => self::lostZero($numTotal['taxMoney']),
            'money'           => self::lostZero($numTotal['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId     = $this->get('templateId');
        $checkedId      = $this->get('checkedId') ? explode(',', $this->get('checkedId')) : [];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $data = [];
            /***********标题**********/
            $title = [];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']) {
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)) {
                $result = find(array(
                    "table" => "sale_send_order_detail as a join sale_send_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
                    'field' => "a.*,b.orderNo,b.recordDate,b.contractId,b.khid,c.code,c.name as materialName,c.model,b.actual_delivery_date,b.manager,'销货' as type,b.text",
                    "where" => "a.id in ('" . implode("','", $checkedId) . "') order by a.list desc,a.time desc",
                ))['array'];
            } else {
                $sql    = $_SESSION[self::page]['sql'];
                $result = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array) {
                $column      = [];
                $contract    = query('sales_contract', "id = '$array[contractId]'");
                $saleOrderMx = query('sale_order_detail', "id = '$array[saleOrderMxId]'");
                $saleOrder   = query('sale_order', "id = '$saleOrderMx[orderId]'");
                $kehu        = query('kehu', "khid = '$array[khid]'");
                foreach ($tempFieldAll as $templateField) {
                    if ($templateField['display']) {
                        $column[] = match ($templateField['columnName']) {
                            '单据日期' => $array['recordDate'],
                            '销售发货单号' => $array['orderNo'],
                            '销售单号' => $saleOrder['orderNo'],
                            '合同编号' => $contract['orderNo'],
                            '客户' => $kehu['companyName'],
                            '销售员' => self::findStaff($array['manager']),
                            '产品编码' => $array['code'],
                            '产品名称' => $array['materialName'],
                            '规格型号' => $array['model'],
                            '单位' => $array['unit'],
                            '发货数量' => self::lostZero($array['num'], 'numPrecision'),
                            '单价' => self::lostZero($array['price'], 'pricePrecision'),
                            '未税金额' => self::lostZero($array['money'] - $array['taxMoney'], 'amount'),
                            '税率' => ($array['rate'] * 100) . '%',
                            '税额' => self::lostZero($array['taxMoney'], 'amount'),
                            '价税合计' => self::lostZero($array['money'], 'amount'),
                            '备注' => $array['text'],
                            default => '',
                        };
                    }
                }
                $data[] = $column;
            }

            $text = $this->control['name'] . "导出了销售订单明细表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "销售订单明细表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify = ''): array
    {
        return match ($classify) {
            default => [
                [
                    'columnName' => '单据日期',
                    'aliasName'  => '单据日期',
                ],
                [
                    'columnName' => '销售发货单号',
                    'aliasName'  => '销售发货单号',
                ],
                [
                    'columnName' => '销售单号',
                    'aliasName'  => '销售单号',
                ],
                [
                    'columnName' => '合同编号',
                    'aliasName'  => '合同编号',
                ],
                [
                    'columnName' => '客户',
                    'aliasName'  => '客户',
                ],
                [
                    'columnName' => '销售员',
                    'aliasName'  => '销售员',
                ],
                [
                    'columnName' => '产品编码',
                    'aliasName'  => '产品编码',
                ],
                [
                    'columnName' => '产品名称',
                    'aliasName'  => '产品名称',
                ],
                [
                    'columnName' => '规格型号',
                    'aliasName'  => '规格型号',
                ],
                [
                    'columnName' => '单位',
                    'aliasName'  => '单位',
                ],
                [
                    'columnName' => '发货数量',
                    'aliasName'  => '发货数量',
                ],
                [
                    'columnName' => '单价',
                    'aliasName'  => '单价(元)',
                ],
                [
                    'columnName' => '未税金额',
                    'aliasName'  => '未税金额(元)',
                ],
                [
                    'columnName' => '税率',
                    'aliasName'  => '税率',
                ],
                [
                    'columnName' => '税额',
                    'aliasName'  => '税额(元)',
                ],
                [
                    'columnName' => '价税合计',
                    'aliasName'  => '价税合计(元)',
                ],
                [
                    'columnName' => '备注',
                    'aliasName'  => '备注',
                ],
            ]
        };
    }
}

